package com.zm.demo.shoppingmall.gateway.service;

import com.zm.demo.shoppingmall.order.api.OrderService;
import com.zm.demo.shoppingmall.order.enums.OrderStatusEnum;
import com.zm.demo.shoppingmall.order.model.TOrder;
import com.zm.demo.shoppingmall.product.api.ProductService;
import com.zm.demo.shoppingmall.product.model.TProduct;
import com.zm.demo.shoppingmall.storage.api.StorageService;
import com.zm.demo.shoppingmall.storage.model.TStorage;
import com.zm.demo.shoppingmall.user.api.UserService;
import com.zm.demo.shoppingmall.user.model.TUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @desc:
 * @author: z01140
 * @date: 2021/5/25 10:57
 */
@Component
@Slf4j
public class OrderManager {

    @DubboReference
    ProductService productService;

    @DubboReference
    StorageService storageService;

    @DubboReference
    UserService userService;

    @DubboReference
    OrderService orderService;

    public int order(TOrder order){
        log.info("下单开始");
        TUser user = userService.getUserById(order.getUserId());
        if (user == null){
            log.error("用户{}不存在", order.getUserId());
            throw new IllegalArgumentException("用户不存在");
        }

        TProduct product = productService.getProductByProductNo(order.getProductNo());
        if (product == null){
            log.error("产品{}不存在", order.getProductNo());
            throw new IllegalArgumentException("产品不存在");
        }
        if (product.getProductStatus() != 1){
            log.error("产品不可卖，状态为：{}", product.getProductStatus());
            throw new IllegalArgumentException("产品不可卖");
        }

        LocalDateTime now =  LocalDateTime.now();
        TStorage storage = storageService.getStorageByProductNo(order.getProductNo(), now);
        if (storage == null){
            log.error("产品{}的库存不存在", order.getProductNo());
            throw new IllegalArgumentException("库存不存在");
        } else if (storage.getAvailableCnt() < order.getProductCnt().intValue()){
            log.error("产品{}库存不足，订单库存：{}，可用库存：{}", order.getProductNo(), order.getProductCnt() ,storage.getAvailableCnt());
            throw new IllegalArgumentException("库存不足");
        }else {
            storage.setAvailableCnt(storage.getAvailableCnt() - order.getProductCnt().intValue());
            storage.setLockCnt(storage.getLockCnt() + order.getProductCnt().intValue());
            int r = storageService.updateStorage(storage);
            if (r == 0){
                log.error("库存更新失败");
                throw new IllegalArgumentException("库存更新失败");
            }
        }
        order.setOrderStatus(OrderStatusEnum.NO_DEAL.getCode());
        int r = orderService.addOrder(order);
        log.info("下单成功");
        return  r;
    }

}
